package net.uman.framework.modules.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;

public class MessageHelper {
	private static Properties props = new Properties();

	static {
		InputStream is = MessageHelper.class
				.getResourceAsStream("/messages.properties");
		try {
			props.load(new InputStreamReader(is, "UTF-8"));
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static List<String> getReasonKeys() {
		return getKeyStartsWith("return.reason.");
	}
	
	/**
	 * 订单取消原因
	 * @return
	 */
	public static List<String> getCancelKeys4Buy() {
		return getKeyStartsWith("cancel.buy.reason.");
	}
	
	/**
	 * 退单取消原因
	 * @return
	 */
	public static List<String> getCancelKeys4Return() {
		return getKeyStartsWith("cancel.return.reason.");
	}
	/**
	 * 读取message_zh_CN.properties文件
	 * @param key 
	 * @param objects 参数名 (给properties配置文件中{0}{1}赋值) 
	 * @return
	 */
	public static String getMessagePro(String key,Object ...objects){
		ResourceBundle bundle = ResourceBundle.getBundle("message",Locale.CHINA);
		return MessageFormat.format(bundle.getString(key),objects);
	}
	
	
	public static List<String> getKeyStartsWith(String s) {
		List<String> keys = new ArrayList<String>();
		for (Object key : props.keySet()) {
			String s1 = (String) key;
			if (s1.startsWith(s)) {
				keys.add(s1);
			}
		}
		return keys;
	}

	public static String getMessage(String key) {
		if (key == null) {
			return null;
		}
		return props.getProperty(key);
	}

	/**
	 * 封装返回key和value
	 * 用于门店订单获取退货原因，形成需要的数据结构
	 * @return
	 */
	public static List<String> getMessageList() {
		List<String> messageList = new ArrayList<String>();
		List<String> keys = getReasonKeys();
		for (String key : keys) {
			String message = key;
			String name = getMessage(key);
			messageList.add("{message:'" + message + "'," + "name:'" + name
					+ "'}");
		}
		return messageList;
	}
	
	public static void main(String[] args) {
		// List<String> keys = getReasonKeys();
		// System.out.println("keys:"+keys);
		// for (String key : keys) {
		// System.out.println("key:"+key+" "+getMessage(key));
		// }
		System.out.println(getMessagePro("auditlog.systemmanagement.login.success",new Object[]{"cnxk","b"}));

	}
}
